angular.module('starter.factory', [])
  .factory('signatureFactory', function (fileFactory) {
    return {
      init: function (domID, option) {
        // option refer to http://git.oschina.net/Simar/signature_pad
        var canvas = document.getElementById(domID);
        var signaturePad = new SignaturePad(canvas, option);
        return signaturePad;
      },
      saveImage: function (signaturePad, imagePath) {
        var data = signaturePad.toDataURL('image/jpeg');
        //fileOptions
        return fileFactory.saveFilesToDevice();
      }
    }
  })
  .factory('fileFactory', function ($q) {
    return {
      createDir: function (basePath, folderName, overwriteFlg) {
        return $cordovaFile.createDir(basePath, folderName, overwriteFlg)
          .then(function (result) {

          }, function (error) {
            error.errorInfo = "Create Directory Failed";
            error.basePath = basePath;
            error.basePath = folderName;
          });
      },
      createDirTaskPromiseFun: function (basePath, folderName, overwriteFlg) {
        var thisService = this;
        return function getCreateDirFunction() {
          return thisService.createDir(basePath, folderName, overwriteFlg);
        }
      },
      checkAndCreateDir: function (fileOptions) {
        var myDefer = $q.defer();
        var folderPath = fileOptions.folderPath + "";
        var fullPath = getFullFilePath(fileOptions.basePath, fileOptions.folderPath);
        var thisService = this;
        var basePath = fileOptions.basePath;
        $cordovaFile.checkDir(basePath, folderPath).then(function (success) {
          myDefer.resolve(fullPath);
        }, function (IO) {
          var promiseListFun = [];
          var folderNames = folderPath.split("/");
          var newBase = basePath;
          for (var i = 0; i < folderNames.length; i++) {
            if (i > 0) {
              newBase += "/" + folderNames[i - 1];
            }
            promiseListFun.push(thisService.createDirTaskPromiseFun(newBase, folderNames[i], false));
          }
          promiseListFun.reduce(function (promise, task, currentIndex, promiseArray) {
            return promise.then(task).then(function (result) {
              if (currentIndex >= (promiseArray.length - 1)) {
                myDefer.resolve(fullPath);
              }
            }, function (error) {
              if (currentIndex >= (promiseArray.length - 1)) {
                myDefer.resolve(fullPath);
              }
            });
          }, $q.when(true));
        })
        return myDefer.promise;
      },
      saveFilesToDevice: function (fileOptions) {
        var deferred = $q.defer();
        var filePath = fileOptions.basePath + "/" + fileOptions.folderPath;
        this.checkAndCreateDir(fileOptions.folderPath)
          .then(function (result) {
            return $cordovaFile.createFile(filePath, fileOptions.fileName, false);
          })
          .then(function (result) {
            deferred.resolve(result);
          }, function (error) {
            error.errorInfo = "Check And Create File Failed";
            deferred.reject(error);
          });
        return deferred.promise;
      },
    }
  })
  .factory('baiduGPSFactory', function () {
    return {
      getLocation: function (successCallback, failedCallback) {
        baidu_location.getCurrentPosition(successCallback, failedCallback);
      }
    }
  })
  .factory('pdfViewFactory', function () {
    return {
      // show: function (url) {  not fit cn
      //   var options = {
      //     title: 'PDF',
      //     documentView: {
      //       closeLabel: 'close'
      //     },
      //     navigationView: {
      //       closeLabel: 'close2'
      //     },
      //     email: {
      //       enabled: false
      //     },
      //     print: {
      //       enabled: false
      //     },
      //     openWith: {
      //       enabled: false
      //     },
      //     bookmarks: {
      //       enabled: false
      //     },
      //     search: {
      //       enabled: false
      //     },
      //     autoClose: {
      //       onPause: false
      //     }
      //   }
      //   cordova.plugins.SitewaertsDocumentViewer.canViewDocument(
      //     url, 'application/pdf', options,
      //     function () {
      //       window.console.log('document can be shown');
      //     },
      //     function (appId, installer) {
      //       if (confirm("Do you want to install the free PDF Viewer App " +
      //           appId + " for Android?")) {
      //         installer();
      //       }
      //     },
      //     function () {
      //       window.console.log('document cannot be shown');
      //       //e.g. track document usage
      //     },
      //     function (error) {
      //       window.console.log(error);
      //       alert("Sorry! Cannot view document.");
      //     });
      // }
    }
  })
